﻿<%@ WebHandler Language="C#" Class="UpdateCustomerRelation" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using LdExpress;

public class UpdateCustomerRelation : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";


        int nPermissions = 0;
        if (context.Request.Params["page"] == "customeractive")
        {
            if (context.Session["ActiveCust"] != null) nPermissions = int.Parse(context.Session["ActiveCust"].ToString());
        }

        if (context.Session["superadmin"] != null
            && int.Parse(context.Session["superadmin"].ToString()) >= 7)
            nPermissions = 10;

        if (nPermissions <= 0)
        {
            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject("ACCESS DENIED"));
            return;
        }
        var vrs = context.Request.Params["version"];
        if (string.IsNullOrEmpty(vrs))
        {
            UpdateCustomerActiveV1(context);
        }
        else if (vrs == "2")
        {
            UpdateCustomerActiveV2(context);
        }
    }

    private void UpdateCustomerActiveV1(HttpContext context)
    {
        try
        {
            string Goods = context.Request.Params["Goods"].Trim();
            string GoodsEx = context.Request.Params["GoodsEx"].Trim();
            string Name = context.Request.Params["Name"].Trim();
            string Code = context.Request.Params["Code"].Trim();
            string Address = context.Request.Params["Address"].Trim();
            string Tel = context.Request.Params["Tel"].Trim();
            string Mobile = context.Request.Params["Mobile"].Trim();
            string Email = context.Request.Params["Email"].Trim();
            string Social = context.Request.Params["Social"].Trim();
            string Pic = context.Request.Params["pic"].Trim();
            string Position = context.Request.Params["Position"].Trim();
            string Routers = context.Request.Params["Routers"].Trim();
            string Vols = context.Request.Params["Vols"].Trim();
            long ID = long.Parse(context.Request.Params["ID"].Trim());
            string Pol = context.Request.Params["Pol"].Trim();
            string Report = context.Request.Params["Report"].Trim();

            string _type = context.Request.Params["type"];

            LdExpress.CustomerActive obj = new LdExpress.CustomerActive();

            if (Name.Trim() == "")
            {
                context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject("NAME_BLANK"));
                return;
            }

            obj.ID = ID;
            obj.Load(LdExpress.GV.cn, LdExpress.GV.trans);
            if (obj == null)
                return;

            //obj.Name = Name;
            obj.Name = new System.Text.RegularExpressions.Regex(@"\s+").Replace(Name, " ");
            obj.Name = System.Text.RegularExpressions.Regex.Replace(obj.Name.ToLower(), "[A-Z]", delegate(System.Text.RegularExpressions.Match match)
            {
                string temp = match.ToString();
                return char.ToLower(temp[0]).ToString();
            });
            obj.Name = System.Text.RegularExpressions.Regex.Replace(obj.Name, "\\b[\\w]\\w*", delegate(System.Text.RegularExpressions.Match match)
            {
                string temp = match.ToString();
                return char.ToUpper(temp[0]).ToString() + temp.Substring(1);
            });
            obj.Code = Code;
            obj.Address = Address;
            obj.Tel = Tel;
            obj.Mobile = Mobile;
            obj.Email = Email;
            obj.Pic = Pic;
            obj.Position = Position;
            obj.Social = Social;
            obj.Routers = Routers;
            obj.Vols = Vols;
            if (obj.Archive != 2)
                obj.LastUpdate = DateTime.Now;
            obj.Pol = Pol;
            obj.Report = Report;
            Customers cus = new Customers();
            if (obj.PicID > 0)
            {
                //cus.ID = obj.PicID;
                //cus.Load(LdExpress.GV.cn, LdExpress.GV.trans);
                //cus.HoTen = obj.Pic;
                //cus.Save(LdExpress.GV.cn, LdExpress.GV.trans);
            }
            else if (obj.Pic != "")
            {
                cus.HoTen = obj.Pic;
                obj.PicID = cus.Save(LdExpress.GV.cn, LdExpress.GV.trans);
            }

            if (!string.IsNullOrEmpty(_type))
            {
                //if (LdExpress.CustomerActive.IsCodeExisting(obj.Code, obj.ID, LdExpress.GV.cn, LdExpress.GV.trans))
                //{
                //    obj.Duplicate = 1;
                //}
                //else
                //    obj.Duplicate = 0;
            }
            else
            {
                obj.Goods = Goods;
                obj.GoodsEx = GoodsEx;
            }

            obj.Save(LdExpress.GV.cn, LdExpress.GV.trans);
            LdExpress.UserObjectsLog.SaveObjectActionLog(long.Parse(context.Session["logined_id"].ToString()), "CustomerActive", "Edit", LdExpress.GV.cn, LdExpress.GV.trans);
            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(DateTime.Now.ToString("dd-MM-yyyy")));
        }
        catch (Exception ex)
        {
            context.Response.Write(ex.Message + ex.StackTrace != null ? ex.StackTrace.ToString() : "");
        }
    }

    private void UpdateCustomerActiveV2(HttpContext context)
    {
        string items = context.Request.Params["items"];
        List<LdExpress.CustomerActive> udpitems = Newtonsoft.Json.JsonConvert.DeserializeObject<List<LdExpress.CustomerActive>>(items);
        string ids = "";
        ids = string.Join(",", udpitems.Select(q => q.ID));
        System.Data.DataSet ds = new System.Data.DataSet();
        string condition = "";
        if (!string.IsNullOrEmpty(ids))
        {
            condition = " and tbl_CustomerActive.ID in (" + ids + ")";
        }
        else
        {
            context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject("not valid"));
        }
        int nNumOfPages = 0;
        int totalitem = 0;
        LdExpress.CustomerActive.GetList(condition, "", 999, 1, out nNumOfPages, out totalitem, out ds, LdExpress.GV.cn, LdExpress.GV.trans);
        Array arr = udpitems.ToArray();

        if (ds.Tables.Count > 0)
        {
            foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
            {
                long ID = long.Parse(dr["ID"].ToString().Trim());

                CustomerActive newcus = udpitems.First(q => q.ID == ID);
                CustomerActive obj = new CustomerActive();

                string Goods = dr["Goods"].ToString().Trim();
                string GoodsEx = dr["GoodsEx"].ToString().Trim();
                string HsGoods = dr["HsGoods"].ToString().Trim();
                string HsGoodsEx = dr["HsGoodsEx"].ToString().Trim();
                string Name = dr["Name"].ToString().Trim();
                string Code = dr["Code"].ToString().Trim();
                string Address = dr["Address"].ToString().Trim();
                string Tel = dr["Tel"].ToString().Trim();
                string Mobile = dr["Mobile"].ToString().Trim();
                string Email = dr["Email"].ToString().Trim();
                string Social = dr["Social"].ToString().Trim();
                string Pic = dr["pic"].ToString().Trim();
                string Position = dr["Position"].ToString().Trim();
                string Routers = dr["Routers"].ToString().Trim();
                string Vols = dr["Vols"].ToString().Trim();
                string Pol = dr["Pol"].ToString().Trim();
                string Report = dr["Report"].ToString().Trim();
                long _type = long.Parse(dr["ListType"].ToString());

                //items:[{'ID':'497','Name':'C.Ty Tnhh Nhựa Và Cao Su Kiến Phát Việt Nam','Address':'sds','Pic':'','Position':'','Tel':'','Mobile':'','Email':'','Social':'','Pol':'','Routers':'','Vols':'','Report':'','Goods':'','ListType':1,'UserID':1,'Description':'','Sort':0,'Owner':0,'Duplicate:0,'Level':0,'AutoLevel:0,'LastUpdate':'Thu Feb 21 2013'}]

                if (Name.Trim() == "")
                {
                    context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject("NAME_BLANK"));
                    return;
                }

                obj.ID = ID;
                obj.Load(LdExpress.GV.cn, LdExpress.GV.trans);
                if (obj == null)
                    return;

                obj.Name = new System.Text.RegularExpressions.Regex(@"\s+").Replace(Name, " ");
                obj.Name = System.Text.RegularExpressions.Regex.Replace(obj.Name.ToLower(), "[A-Z]", delegate(System.Text.RegularExpressions.Match match)
                {
                    string temp = match.ToString();
                    return char.ToLower(temp[0]).ToString();
                });
                obj.Name = System.Text.RegularExpressions.Regex.Replace(obj.Name, "\\b[\\w]\\w*", delegate(System.Text.RegularExpressions.Match match)
                {
                    string temp = match.ToString();
                    return char.ToUpper(temp[0]).ToString() + temp.Substring(1);
                });
                obj.Code = HttpUtility.HtmlDecode(newcus.Code);
                obj.Address = HttpUtility.HtmlDecode(newcus.Address);
                obj.Tel = HttpUtility.HtmlDecode(newcus.Tel);
                obj.Mobile = HttpUtility.HtmlDecode(newcus.Mobile);
                obj.Email = HttpUtility.HtmlDecode(newcus.Email);
                obj.Pic = HttpUtility.HtmlDecode(newcus.Pic);
                obj.Position = HttpUtility.HtmlDecode(newcus.Position);
                obj.Social = HttpUtility.HtmlDecode(newcus.Social);
                obj.Routers = HttpUtility.HtmlDecode(newcus.Routers);
                obj.Vols = HttpUtility.HtmlDecode(newcus.Vols);
                if (obj.Archive != 2)
                    obj.LastUpdate = DateTime.Now;
                obj.Pol = HttpUtility.HtmlDecode(newcus.Pol);
                obj.Report = HttpUtility.HtmlDecode(newcus.Report);
                obj.Goods = HttpUtility.HtmlDecode(newcus.Goods);
                obj.GoodsEx = HttpUtility.HtmlDecode(newcus.GoodsEx);
                obj.HsGoods = HttpUtility.HtmlDecode(newcus.HsGoods);
                obj.HsGoodsEx = HttpUtility.HtmlDecode(newcus.HsGoodsEx);
                obj.Name = HttpUtility.HtmlDecode(newcus.Name);

                //khong update inline
                obj.ListType = long.Parse(dr["ListType"].ToString());
                obj.UserID = long.Parse(dr["UserID"].ToString());
                //obj.GoodsEx = dr["GoodsEx"].ToString();
                //obj.Goods = dr["Goods"].ToString();
                obj.Description = dr["Description"].ToString();
                obj.Sort = int.Parse(dr["Sort"].ToString());
                obj.Owner = long.Parse(dr["Owner"].ToString());
                obj.Duplicate = long.Parse(dr["Duplicate"].ToString());
                obj.Level = long.Parse(dr["Level"].ToString());
                obj.AutoLevel = long.Parse(dr["AutoLevel"].ToString());
                obj.CusLevel_Limit = dr["CusLevel_Limit"].ToString();
                obj.CusLevel_Liabilities = dr["CusLevel_Liabilities"].ToString();
                obj.CusLevel_Note = dr["CusLevel_Note"].ToString();
                obj.CusLevel_TB = dr["CusLevel_TB"].ToString();
                obj.CusLevel_Debts_Incurred = dr["CusLevel_Debts_Incurred"].ToString();
                obj.ListType = _type;
                Customers cus = new Customers();
                if (obj.PicID > 0)
                {
                    //cus.ID = obj.PicID;
                    //cus.Load(LdExpress.GV.cn, LdExpress.GV.trans);
                    //cus.HoTen = obj.Pic;
                    //cus.Save(LdExpress.GV.cn, LdExpress.GV.trans);
                }
                else if (obj.Pic != "")
                {
                    cus.HoTen = obj.Pic;
                    obj.PicID = cus.Save(LdExpress.GV.cn, LdExpress.GV.trans);
                }
                obj.Save(LdExpress.GV.cn, LdExpress.GV.trans);
            }
            LdExpress.UserObjectsLog.SaveObjectActionLog(long.Parse(context.Session["logined_id"].ToString()), "CustomerActive", "Edit", LdExpress.GV.cn, LdExpress.GV.trans);
        }

        context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(items));
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    private void Output(string message, HttpContext context)
    {
        context.Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(new { Message = message, Date = DateTime.Now.ToString("dd-MM-yyy") }));
    }
}